<?php

namespace app\service\admin\system;

use app\model\Common;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class AdminsService
{

    /**
     * 角色列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getAllRoleList(): array
    {
        return Common::getAllData(RoleTable, [], ['id', 'name']);
    }

    /**
     * 管理列表
     * @param array $request
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getList(array $request): array
    {
        $page = $request['page'] ?? 1;
        $size = $request['size'] ?? 10;
        $so = '';
        $filter = [];
        if ($so) {
            $filter[] = ['account', 'like', $so . '%'];
        }
        return Common::getList(AdminTable, $filter, ['id', 'account', 'status', 'role_id','mobile', 'create_time'], $page, $size);
    }

    /**
     * 添加
     * @param array $request
     * @return int|string
     */
    public static function add(array $request)
    {
        $request['password'] = password_hash($request['password'], PASSWORD_BCRYPT);
        return Common::addData(AdminTable, $request);
    }

    /**
     * 修改
     * @param array $request
     * @return int
     * @throws DbException
     */
    public static function update(array $request): int
    {
        if (isset($request['password']) && $request['password']) {
            $request['password'] = password_hash($request['password'], PASSWORD_BCRYPT);
        } else {
            unset($request['password']);
        }
        return Common::updateData(AdminTable, ['id' => $request['id']], $request);
    }

    /**
     * 删除
     * @param array $request
     * @return false|int|string
     * @throws DbException
     */
    public static function delete(array $request)
    {
        if (!isset($request['data']) || !$request['data']) {
            return false;
        }
        $ids = [];
        foreach ($request['data'] as $v) {
            $ids[] = $v['id'];
        }
        return Common::deleteData(AdminTable, ['id' => $ids]);
    }

}